package org.i0o.webplus.commons.util.populator.converters;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

/**
 * @author <a href="mailto:781131@gmail.com">HTF</a>
 * @version 2010-5-15
 */
public class JSONConverter {
	/**
	 * 将Object类型转换成json字符串
	 * 
	 * @param obj object对象
	 * @return json字符串
	 */
	public static String objectToJson(Object obj) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setJavaPropertyFilter(new PropertyFilter() {

			@Override
			public boolean apply(Object obj, String name, Object value) {
				if ("start".equals(name) || "limit".equals(name) || "sort".equals(name) || "dir".equals(name) || "callback".equals(name)) return true;
				return false;
			}

		});
		JSONObject object = JSONObject.fromObject(obj,jsonConfig);
		return object.toString();
	}

	/**
	 * 将Array数组 转换成json字符串
	 * 
	 * @param list
	 * @return
	 */
	public static String arrayToJson(Collection<?> list) {
		JSONArray array = JSONArray.fromObject(list);
		return array.toString();
	}

	/**
	 * 将Map类型转换成json字符串
	 * 
	 * @param map map对象
	 * @return json字符串
	 */
	public static String mapToJson(Map<?, ?> map) {
		return objectToJson(map);
	}

	/**
	 * List 转换成ExtGrid使用的json字符串数据
	 * 
	 * @param list
	 * @return
	 */
	public static String listToExtGridData(List<?> list) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setJavaPropertyFilter(new PropertyFilter() {

			@Override
			public boolean apply(Object obj, String name, Object value) {
				if ("start".equals(name) || "limit".equals(name) || "sort".equals(name) || "dir".equals(name) || "callback".equals(name)) return true;
				return false;
			}

		});
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		return jsonArray.toString();
	}

}
